
{% extends 'layout/index.html' %}

{% load custom_tag %}

{% block css %}
       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
       <link rel="stylesheet" href="/static/plugins/iCheck/blue.css">

{% endblock %}


{% block conent %}

    <ol class="breadcrumb">
      <li  > <a href="/">主机管理</a></li>
      <li  class="active">批量命令</li>
    </ol>

    <div class="panel-body" >

        {% include 'host/host_list_menu_component.html' %}
        {% include 'host/hosts_multi_cmd_component.html' %}

    </div>

    {% include 'host/multi_task_modal_box.html' %}

{% endblock %}


{% block js %}

{#    注释的这里代表的是 好看的---> input 标签的使用。#}
    <script src="/static/plugins/iCheck/icheck.min.js"></script>
{#    #}

    <script type="text/javascript" >
    $(function () {
        $('input').iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_square-blue',
          increaseArea: '10%'  // optional

        });

    });

{#    注意的是被ichek 包装过的inuput 不能被正常的点击事件了，所以利用他的方法进行点击事件的函数调用。#}
    $('input').on('ifClicked',function(event){
        AddCounter(this);

    });
    function  AddCounter(ele) {
        // 统计选中主机数量。
        //$("#selected_host_count")
        console.log( '111111111' );
        var current_counter = parseInt($(ele).parent().parent().parent().parent().parent().parent().siblings().find("#selected_host_count").text());

        console.log(current_counter);

        if ($(ele).prop("checked") == true){
            //之前没选
            $(ele).parent().parent().parent().parent().parent().parent().siblings().find("#selected_host_count").html( current_counter-1);
        }else {
            $(ele).parent().parent().parent().parent().parent().parent().siblings().find("#selected_host_count").html( current_counter+1);
        }
    }


   $(".checkbox-toggle").click(function () {
          var clicks = $(this).data('clicks');
          if (clicks) {
            //Uncheck all checkboxes 反选
            console.log( $(this).parent().siblings().find('input'));
            $(this).parent().siblings().find('input').iCheck("uncheck");
            $(".fa", this).removeClass("fa-check-square-o").addClass('fa-square-o');
{#            $(this).parent().parent().parent().parent().parent().parent().siblings().find("#selected_host_count").html(0);#}
            $(this).parent().find('#selected_host_count').html('0')

          } else {
            //Check all checkboxes 全选
            $(this).parent().siblings().find('input').iCheck("check");
            $(".fa", this).removeClass("fa-square-o").addClass('fa-check-square-o');
             $(this).parent().find('#selected_host_count').html($(this).parent().siblings().find('input').length);

          }
          $(this).data("clicks", !clicks);
    });

   $("#modal-410662").click(function(){
        var cmd = $.trim($("#cmd").val());
        console.log(cmd);

        $("#modal_content").html(cmd);


        var task_expire_time = $("select[name='task_expire_time']").val();

        postDic = {
            'selected_hosts':[],
            'expire_time':task_expire_time,
            'cmd':cmd
            };
        var err_msg=[];
        //run form submistion check before submit

        var selected_hosts = $("div[aria-checked=true]").find('input');

        if (selected_hosts.length == 0){
            err_msg.push("未选中任何主机执行任务！");
        }
        $(selected_hosts).each(function(){
            postDic["selected_hosts"].push($(this).attr("id"));
        });
        postDic["selected_hosts"] = JSON.stringify(postDic["selected_hosts"]);

        if(cmd.length ==0 ){
            err_msg.push("输入的命令不能为空!");
        };


        if (err_msg.length == 0){ // passed form submition check
            console.log(postDic);
            $("#taskRunConfirmModal").modal('show');

        }else{
            console.log(err_msg + err_msg.length);
            console.log(selected_hosts.length);
            show_alert(err_msg);
        }


    });

   function submit_task(ele,post_url){
            // ajax提交任务的 postDic 字典形式。
            //console.log(ele);
            $(ele).attr('disabled','true');

            $.post(post_url, postDic,function(callback){
                console.log(callback);

                if (callback != 'TaskCreatingError'){
{#                    alert(callback);#}
                    $("#modal_content").html("任务创建成功! 任务编号:" + callback);
                    $("#modal_content").attr("style","color:green;font:bold");
                    $(".task_result").html("");
                    $("#file-download-to-local").attr("task_id",callback); // only works when task_type = file_get
                    GetTaskResult(callback,'refresh');
                }else{
                    $("#modal_content").html("任务创建失败，请查看相关日志进行调试！");
                    $("#modal_content").attr("style","color:red;font:bold")

                }
                });
    }

   function GetTaskResult(task_id,run_type){
        if (run_type=='refresh'){

            PrintTaskResult(task_id);
            ResultRefresh = setInterval(function(){
                PrintTaskResult(task_id);
            },2000);
        }else{
            var one_time_run = null ;
        }
   }

   function PrintTaskResult(task_id){
        $.getJSON( "{% url 'host_multitask_res' %}", {'task_id':task_id},function(callback) {
{#            $("#current_task_id span").html(callback['summary'].id);   // id:22#}
{#            $("#total_tasks span").html(callback['summary'].host_num); // host_num:4#}
{#            $("#finished_tasks span").html(callback['summary'].success_num); // finshed_mun:0#}
{#            $("#failed_tasks span").html(callback['summary'].failed_num); #}  // failed_num: 0
{#            $("#unkown_tasks span").html(callback['summary'].init_num);#}  //  unkonw_num: 0
              console.log(callback['summary']);
{#            console.log(callback['detail']);#}

              $.each(callback['detail'], function (key, log) {
                    console.log(callback['detail'][key]);
    
                    var d = callback['detail'][key];
                    
                    if (d.result == 'success') {
                        var task_res = '<span style="padding:  5px 5px"  class="pull-right badge bg-blue">任务结果:' + d.result + '</span>';
                    } else if (d.result == 'failed') {
                        var task_res = '<span style="padding:  5px 5px"  class="pull-right badge bg-red">任务结果:' +  d.result + '</span>';
                    } else {   // (d.result == 'init')
                        var task_res = '<span style="padding:  5px 5px"  class="pull-right badge bg-aqua">任务结果:' + d.result + '</span>';
                        console.log(d.result)
                    }
    
                    if ($(".task_result div[result='host_" + d.host_id + "'] pre").attr("style")=="display: none;"){
                        var res_detail = " <div class='box-body' style='display: none;'>" + "<pre>" + d.event_log + "</pre>" + "</div>";
                    }else{
                        var res_detail = " <div class='box-body' style='display: block;'>" + "<pre>" + d.event_log + "</pre>" + "</div>";
                    }
                    

                    var h4_ele = "<div class='box-header  with-border' style='padding: 5px 5px 5px 5px' >";
    
                    var host_info_ele = h4_ele + "<button type='button' class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"
                        + " <h3 class='box-title'>" + "主机:"
                        + d.username + "@" + d.ip_addr
                        + "</h3>"
                        + "<small  style='padding: 5px 5px'  class='label pull-right bg-blue'>" +  "系统:" + d.system
                        + "</small>" +  task_res + "</div>" + res_detail;
    
                    if ($(".task_result div[result='host_" + d.host_id + "']").length > 0) {
                        $(".task_result div[result='host_" + d.host_id + "']").html(host_info_ele);
                    } else {
                        var res_div = "<div result='host_" + d.host_id + "'class='box box-default box-solid'>" + host_info_ele + "</div>";
                        $(".task_result").append(res_div);
                    }
            
              });//end each


              if (callback['summary'].init_num == 0 ){

                if (typeof ResultRefresh !='undefined' ){
                    clearInterval(ResultRefresh);
                    $("#submit_task_confirm").prop("disabled",false);
                 }
              }
            
        }); //end getJSON
    }



   </script>

{% endblock %}